package com.wtao.imagereader;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.SurfaceTexture;
import android.os.Bundle;
import android.util.Log;
import android.util.Size;
import android.view.TextureView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.wtao.imagereader.aicamera.CameraV2Manager;
import com.wtao.imagereader.aicamera.CameraV2Proxy;
import com.wtao.imagereader.listener.NoMultiClickListener;
import com.wtao.imagereader.utils.AutoFitTextureView;

import java.util.Arrays;

/**
 * 这个界面的代码从Ah8 camera里的主界面挪过来的代码，去除了databinding
 * 去除了界面多余的元素，只保留了TextureView和切换摄像头的按钮，放到这个界面试试，看能否打开车外摄像头
 * 结果发现是可以正常打开的
 */
public class AiCameraMainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = MainActivity.class.getSimpleName();
    public static final String ROUTEREVENT_TAKEPHOTO = "takePhoto";
    private final String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA};
    private boolean mIsPaused = false;//界面是否退到后台
    //拍照倒计时图片显示
    public static boolean isTakingPhoto = false;
    //private static final long TOTALROM = (long) (7.5 * 1024);
    private static final long TOTALROM = (long) (2 * 1024);
    private int leftTime = 2;
    private ImageView mLeftTimeView;//倒计时图片显示
    private boolean mTakeAddVoice = true;//开关，声音播放是否打开，默认打开，按理设置里弄一个switch好些
    private AutoFitTextureView texture;
    public boolean textureCreated = false;
    private SurfaceTexture surfaceTexture;
    private boolean permissionGetted;
    private Size mPreviewSize;
    private ImageView ivChangeCamera;

    private ActivityResultLauncher<String[]> permissionRequest = registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), granteds -> {
        boolean parsed = true;
        Log.e(TAG, "permission result : class->" + granteds.getClass());
        for (String key : granteds.keySet()) {
            parsed &= granteds.get(key);
        }
        permissionGetted = parsed;
        afterPermissionInitCamera();
    });


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        Log.e(TAG, "onRequestPermissionsResult: rc=" + requestCode + "\n" + Arrays.toString(permissions) + "\n" + Arrays.toString(grantResults));
        boolean enable = true;
        for (int i = 0; i < grantResults.length; i++) {
            if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                enable = false;
                break;
            }
        }
        permissionGetted = enable;
        Log.e(TAG, "permissionGetted=" + permissionGetted + " requestCode=" + requestCode);
        afterPermissionInitCamera();
    }

    private void afterPermissionInitCamera() {
        //第一次打开时弹框，没有走到onSurfaceTextureAvailable里去，光initCamera摄像头打开是是90度差异的画面，所以加了下面的代码
        //mBinding.texture.setAspectRatio(mBinding.texture.getWidth(), mBinding.texture.getHeight());
        //mPreviewSize = new Size(mBinding.texture.getWidth(), mBinding.texture.getHeight());

        //想着通过下面方式解决有一个摄像头录制视频底部绿色问题，好像无效
        String cameraId = CameraV2Manager.getInstance().getCurrentCameraId();

        mPreviewSize = new Size(1920, 1080);

        Log.e(TAG, "cameraId=" + cameraId);
        texture.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());
        Log.e(TAG, "mPreviewSize=" + mPreviewSize.getWidth() + " height=" + mPreviewSize.getHeight());
        cameraChange(false);
        texture.setScaleX(-1f);
        CameraV2Manager.getInstance().setFailedCallback(failedCallback);

        CameraV2Manager.getInstance().openCamera(texture.getSurfaceTexture());

    }

    private CameraV2Proxy.FailedCallback failedCallback = new CameraV2Proxy.FailedCallback() {
        @Override
        public void failed() {

        }
    };

    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ai_camera);
        Log.e(TAG, "onCreate");
        initView();
        initData();
    }

    private void cameraChange(boolean failed) {

    }

    private void requestPermission() {
        for (String str : permissions) {
            if (ContextCompat.checkSelfPermission(this, str) != PackageManager.PERMISSION_GRANTED) {
                permissionRequest.launch(permissions);
                return;
            }
        }
        permissionGetted = true;
        afterPermissionInitCamera();
    }


    protected void initData() {

        CameraV2Manager.getInstance().getCameraInfo();

    }

    protected void initView() {

        Log.e(TAG, "initView");
        texture = findViewById(R.id.texture);
        ivChangeCamera = findViewById(R.id.ivChangeCamera);
        texture.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
            @Override
            public void onSurfaceTextureAvailable(@NonNull SurfaceTexture surface, int width, int height) {
                Log.e(TAG, "initCamera onSurfaceTextureAvailable width=" + width + " height=" + height);
                surfaceTexture = surface;
                textureCreated = true;
                afterPermissionInitCamera();
            }

            @Override
            public void onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surface, int width, int height) {
                Log.e(TAG, "onSurfaceTextureSizeChanged width=" + width + " height=" + height);
            }

            @Override
            public boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surface) {
                Log.e(TAG, "onSurfaceTextureDestroyed");
                return false;
            }

            @Override
            public void onSurfaceTextureUpdated(@NonNull SurfaceTexture surface) {

            }
        });


        //都设置防止连续点击事件，如果需要设置双击事件，就不用onClickListener成员变量自己定义

        ivChangeCamera.setOnClickListener(this);
        findViewById(R.id.btnExit).setOnClickListener(this);


    }


    @Override
    protected void onResume() {
        super.onResume();
        CameraV2Manager.getInstance().setupCamera();
        mIsPaused = false;
        Log.e(TAG, "onResume");

    }


    @Override
    protected void onPause() {
        super.onPause();
        Log.e(TAG, "onPause");
        mIsPaused = true;
        CameraV2Manager.getInstance().closeCamera();
    }


    @Override
    public void onClick(View v) {
        Log.e(TAG, "onClick");
        switch (v.getId()) {
            case R.id.ivChangeCamera: {//切换摄像头
                String cameraId = CameraV2Manager.getInstance().getCurrentCameraId();
                Log.e(TAG, "change camera, current cameraId：" + cameraId);
                switchCamera();
            }
            break;
            case R.id.btnExit:
                finish();
                break;
        }
    }

    //拍照切换摄像头(看当前模式是车内摄像头还是车外摄像头)
    private void switchCamera() {
        Log.e(TAG, " switchCamera()");
        int cameraPreviewWidth = 1920, cameraPreviewHeight = 1080;
        String cameraId = CameraV2Manager.getInstance().getCurrentCameraId();
        Log.e(TAG, "current cameraId：" + cameraId);
        int currentIndex = 0;
        for (int i = 0; i < Constants.cameraIds.size(); i++) {
            if (cameraId == Constants.cameraIds.get(i)) {
                currentIndex = i;
                break;
            }
        }
        int newIndex = (currentIndex + 1) % Constants.cameraIds.size();
        cameraId = Constants.cameraIds.get(newIndex);
        Log.e(TAG, "车内摄像头模式，cameraId=" + cameraId);
        Constants.cameraId = cameraId;
        //按理这里应该从currentSelectedInnerCamera里选，不过currentSelectedInnerCamera里add了 Constants.CAMERA_INNER_FRONT Constants.CAMERA_INNER_BACK两个id，可以直接判断
        //手动拍照应该从可选的摄像头里选择来切换的 currentSelectedInnerCamera里，而不是选车机所有的，为了看拍照图片大小，特意先修改下
        Size size = Constants.getCameraSize(Constants.cameraId);
        if (size != null) {
            cameraPreviewWidth = size.getWidth();
            cameraPreviewHeight = size.getHeight();
            Log.e(TAG, "cameraPreviewWidth=" + cameraPreviewWidth + " cameraPreviewHeight=" + cameraPreviewHeight);
        } else {
            Log.e(TAG, "size null");
        }
        cameraChange(false);
        CameraV2Manager.getInstance().setPreviewSize(cameraPreviewWidth, cameraPreviewHeight);
        CameraV2Manager.getInstance().switchCamera(Constants.cameraId);
        Log.e(TAG, "切换摄像头后:cameraId=" + Constants.cameraId + " cameraPreviewWidth=" + cameraPreviewWidth + " cameraPreviewHeight=" + cameraPreviewHeight);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

}
